package com.jiangnan.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jiangnan.entity.BookRecommendationDTO
import com.jiangnan.entity.Res
import com.jiangnan.repository.RecommendationRepository
import kotlinx.coroutines.launch

class RecommendationViewModel : ViewModel() {

    val recommendationRepository = RecommendationRepository()

    private val _recommendations = MutableLiveData<List<BookRecommendationDTO>>()
    val recommendations: LiveData<List<BookRecommendationDTO>> get() = _recommendations

    private val _rating = MutableLiveData<Res<Double>>()
    val rating: LiveData<Res<Double>> get() = _rating

    private val _toastMessage = MutableLiveData<String>()
    val toastMessage: LiveData<String> get() = _toastMessage

    fun fetchRecommendations(userId: Int, topN: Int = 10) {
        viewModelScope.launch {
            try {
                val response = recommendationRepository.getRecommendations(userId, topN)
                _recommendations.postValue(response)
            } catch (e: Exception) {
                e.printStackTrace()
                _recommendations.postValue(emptyList())
            }
        }
    }

    fun getRating(userId: Int, bookId: Int) {
        viewModelScope.launch {
            try {
                val response = recommendationRepository.getRating(userId, bookId)
                if (response.code == 1){
                    _rating.postValue(response)
                }else{
                    _toastMessage.postValue("获取评分失败")
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _rating.postValue(Res(0, "获取评分失败", null))
            }
        }
    }

}